/*
 * File     : StructureByReferenceStructureField.java
 * Created  : 20 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import static com.googlecode.dni.internal.DniTypes.ABSTRACT_STRUCTURE_TYPE;
import static com.googlecode.dni.internal.DniTypes.STRUCTURE_TYPE;
import static org.objectweb.asm.Opcodes.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import com.googlecode.dni.internal.structure.StructureManager.StructureTypeNames;
import com.googlecode.dni.type.nativetype.NativeTypes;
import com.googlecode.dni.type.nativetype.Unsigned;
import com.googlecode.dni.type.structure.Structure;


/**
 * Encapsulates details of a {@link Structure} (by reference) structure's field
 * used during class generation.
 *
 * @author Matthew Wilson
 */
final class StructureByReferenceStructureField extends StructureField
{

    /** Primitive type for a pointer in 32-bits. */
    private static final PrimitiveType POINTER_32 = PrimitiveType.getType( int.class );

    /** Primitive type for a pointer in 64-bits. */
    private static final PrimitiveType POINTER_64 = PrimitiveType.getType( long.class );


    /** These annotations make no sense. */
    private static final List< Class< ? extends Annotation > > FORBIDDED_ANNOTATION_TYPES =
        new ArrayList< Class< ? extends Annotation > >();

    static
    {
        FORBIDDED_ANNOTATION_TYPES.add( Unsigned.class );
        FORBIDDED_ANNOTATION_TYPES.addAll( NATIVE_SIZED_TYPES );
    }

    private String structureImplName;

    private String structureFactoryImplName;


    /**
     * {@inheritDoc}
     */
    @Override
    void setGetter( final Method getter )
    {
        super.setGetter( getter );

        checkAnnotations( FORBIDDED_ANNOTATION_TYPES );

        // we only need the names here
        Class< ? extends Structure > structureType = getter.getReturnType().asSubclass( Structure.class );
        StructureTypeNames names = getSession().getNames( structureType );
        this.structureImplName = names.getImplName();
        this.structureFactoryImplName = names.getFactoryImplName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    String getCType()
    {
        return "void*";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    int getSize()
    {
        // size in the structure is that of a pointer
        return NativeTypes.POINTER_SIZE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeGetter( final MethodVisitor methodVisitor,
                      final String implName )
    {
        methodVisitor.visitFieldInsn( GETSTATIC,
                                      this.structureFactoryImplName,
                                      "INSTANCE",
                                      "L" + this.structureFactoryImplName + ";" );

        writeGetPointer( methodVisitor );
        if ( NativeTypes.POINTER_SIZE == 4 )
        {
            POINTER_32.writeGet( methodVisitor, false );
            methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                           this.structureFactoryImplName,
                                           "fromPointer",
                                           "(I)L" + STRUCTURE_TYPE + ";" );
        }
        else
        {
            assert NativeTypes.POINTER_SIZE == 8;
            POINTER_64.writeGet( methodVisitor, false );
            methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                           this.structureFactoryImplName,
                                           "fromPointer",
                                           "(J)L" + STRUCTURE_TYPE + ";" );
        }

        methodVisitor.visitTypeInsn( CHECKCAST, this.structureImplName );

        methodVisitor.visitInsn( Opcodes.ARETURN );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeSetter( final MethodVisitor methodVisitor,
                      final String implName )
    {
        writeGetPointer( methodVisitor );

        methodVisitor.visitVarInsn( ALOAD, 1 );
        methodVisitor.visitTypeInsn( CHECKCAST, this.structureImplName );

        methodVisitor.visitMethodInsn( INVOKESTATIC,
                                       ABSTRACT_STRUCTURE_TYPE,
                                       "getAddress",
                                       "(L" + ABSTRACT_STRUCTURE_TYPE + ";)J" );

        if ( NativeTypes.POINTER_SIZE == 4 )
        {
            methodVisitor.visitInsn( L2I );
            POINTER_32.writeSet( methodVisitor );
        }
        else
        {
            assert NativeTypes.POINTER_SIZE == 8;
            POINTER_64.writeSet( methodVisitor );
        }

        methodVisitor.visitInsn( Opcodes.RETURN );
    }

}
